package com.jiang.jixiang.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.UserInfoBean;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.tools.PubDiaUtils;
import com.jiang.jixiang.ui.MainActivity;
import com.jiang.jixiang.ui.RegistInviteActivity;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.ws.universal.tools.Constants;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.DeviceUtils;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:ws
 * @date: 2019/11/11 9:23
 * @desc
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler, NetWorkListener {

    private String TAG = WXEntryActivity.class.getSimpleName();
    // 微信回复的时候会重新创建一个WXEntry
    private IWXAPI api = null;
    private static final int RETURN_MSG_TYPE_LOGIN = 1;  ///< 登录
    private static final int RETURN_MSG_TYPE_SHARE = 2;  ///< 分享


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogcatUtils.e("", " WXEntryActivity oncreate ");
        if (DeviceUtils.getManufacturer().equalsIgnoreCase("Sony")) {
            setTheme(R.style.wxNoActionBar2);
        } else if (DeviceUtils.getManufacturer().equalsIgnoreCase("Xiaomi")) {
            if (DeviceUtils.getModel().equalsIgnoreCase("MIX2")) {
                setTheme(R.style.wxNoActionBar2);
            } else {
                setTheme(R.style.wxNoActionBar);
            }
        } else if (DeviceUtils.getManufacturer().equalsIgnoreCase("Huawei")) {
            if (DeviceUtils.getModel().equalsIgnoreCase("PIC-AL00") || DeviceUtils.getModel().equalsIgnoreCase("HWI-AL00") || DeviceUtils.getModel().equalsIgnoreCase("BAC-AL00") || DeviceUtils.getModel().equalsIgnoreCase("NXT-AL10") || DeviceUtils.getModel().equalsIgnoreCase("KNT-AL10") || DeviceUtils.getModel().equalsIgnoreCase("KNT-AL20") || DeviceUtils.getModel().equalsIgnoreCase("KNT-UL10") || DeviceUtils.getModel().equalsIgnoreCase("FRD-AL10") || DeviceUtils.getModel().equalsIgnoreCase("LND-AL30") || DeviceUtils.getModel().equalsIgnoreCase("LDN-AL20") || DeviceUtils.getModel().equalsIgnoreCase("BKL-AL20") || DeviceUtils.getModel().equalsIgnoreCase("RNE-AL00") || DeviceUtils.getModel().equalsIgnoreCase("LLD-AL20")

            ) {
                setTheme(R.style.wxNoActionBar2);
            } else {
                setTheme(R.style.wxNoActionBar);
            }

        } else if (DeviceUtils.getManufacturer().equalsIgnoreCase("Samsung")) {
            setTheme(R.style.wxNoActionBar2);
        } else {
            setTheme(R.style.wxNoActionBar);
        }
        super.onCreate(savedInstanceState);
        ManageActivity.putActivity("WXEntryActivity", this);
        //这句没有写,是不能执行回调的方法的
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
        api.handleIntent(getIntent(), this);
        //向微信注册
        api.registerApp(Constants.APP_ID);

    }


    @Override
    public void onReq(BaseReq baseReq) {
        LogcatUtils.i(TAG, "onReq" + baseReq.getType());
    }


    @Override
    public void onResp(BaseResp baseResp) {

        LogcatUtils.i(TAG, "WXEntryActivity errCode:---->  " + baseResp.errCode);
        int type = baseResp.getType(); //类型：分享还是登录
        LogcatUtils.i(TAG, "WXEntryActivity type 分享还是登录 :----> " + type);
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                ///< 用户拒绝授权
                finish();
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                ///< 用户取消
                String message = "";
                if (type == RETURN_MSG_TYPE_LOGIN) {
                    message = "取消了微信登录";
                } else if (type == RETURN_MSG_TYPE_SHARE) {
                    message = "取消了微信分享";
                }
                finish();
                break;
            case BaseResp.ErrCode.ERR_OK:
                LogcatUtils.i(TAG, " WXEntryActivity type 登录 :----> " + type);
                if (type == RETURN_MSG_TYPE_LOGIN) {
                    ///< 用户换取access_token的code，仅在ErrCode为0时有效
                    String code = ((SendAuth.Resp) baseResp).code;

                    LogcatUtils.i(" WXEntryActivity wx_code :----> " + code);
                    ///< 这里拿到了这个code，去做2次网络请求获取access_token和用户个人信息

                   /* if (CacheUtils.getBoolean(Constants.WX_Login)) {
                        getAccessToken(code);
                    } else {
                        bindWx(code);
                    }*/
                    loginOther(code, "wechat");

                } else if (type == RETURN_MSG_TYPE_SHARE) {
                    ///< "微信分享成功"
                    finish();
                }
                break;
        }
    }

    //第三方登录
    private void loginOther(String openid, String type) {
        Map<String, String> params = new HashMap<>();
        params.put("openid", openid);
        params.put("push_id", Constants.push_id);
        params.put("type", type);
        okHttpModel.post(ApiUrl.login_Api, params, ApiUrl.login_Api_ID, this);
    }


    /**
     * @param code 根据code再去获取AccessToken
     */
    private void getAccessToken(String code) {

        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        // okHttpModel.post(ApiUrl.wechatloginUrl, params, ApiUrl.wechatlogin_ID, this);
    }


    //验证码实体类 token
    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.login_Api_ID:

                UserInfoBean userInfoBean = GsonUtils.parseJObject(data.toString(), UserInfoBean.class);
                if (userInfoBean != null) {
                    PubDiaUtils.getInstance().saveUserInfo(data.toString());
                }
                CacheUtils.setString(Constants.token, data.optString("token"));
                CacheUtils.setString(Constants.client, "android");
                CacheUtils.setBoolean(Constants.isLogin, true);
                ToastUtils.showShort(commonality.getMessage());
                BaseBusData baseBusData = new BaseBusData(BusCode.LogIn);
                EventBusUtil.postEvent(baseBusData);

                ManageActivity.removeActivity("LoginActivity");
               /* if (userInfoBean.getFirst_login() == 1) {
                    Intent intent = new Intent(getApplication(), RegistInviteActivity.class);
                    startActivity(intent);
                } */
                Intent intent = new Intent(getApplication(), MainActivity.class);
                startActivity(intent);
                this.finish();

                //startActivity(new Intent(WXEntryActivity.this, MainActivity.class));
                break;


        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        ToastUtils.showShort(commonality.getMessage(), 300);
        this.finish();
    }

    @Override
    public void onError(int id, Exception e) {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ManageActivity.removeActivity("WXEntryActivity");
    }

}
